/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2011 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 *
 * --------------------------------------------------------------------------
 * $Id: TcpSender.java 467 2011-09-30 14:23:20Z guillaume.sauthier $
 * --------------------------------------------------------------------------
 */


package org.osami.cilia.adapter.tcp.internal;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.net.SocketFactory;

import fr.liglab.adele.cilia.Data;
import fr.liglab.adele.cilia.framework.ISender;
import org.osgi.service.log.LogService;

/**
 * A {@code TcpCollector} is responsible to load the chain with incoming messages from a TCP endpoint.
 *
 * @author Guillaume Sauthier
 */
public class TcpSender implements ISender {

    /**
     * Remote hostname.
     * Configuration property.
     */
    private String hostname;

    /**
     * TCP port to be used.
     * Configuration property.
     */
    private int port;

    /**
     * LogService.
     */
    private LogService logger;

    /**
     * Live socket.
     */
    private Socket socket;

    public void start() throws Exception {
        SocketFactory factory = SocketFactory.getDefault();
        socket = factory.createSocket(hostname, port);
    }

    public void stop() throws Exception {
        socket.close();
    }

    public void setHostname(String hostname) {
        this.hostname = hostname;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public void setLogger(LogService logger) {
        this.logger = logger;
    }

    public boolean send(Data data) {
        Object content = data.getContent();
        if (content != null) {
            try {
                byte[] serialized = serializeObject(content);
                OutputStream os = socket.getOutputStream();
                os.write(serialized);
                os.flush();
            } catch (IOException e) {
                logger.log(LogService.LOG_ERROR, "Cannot send the Data: " + data);
                return false;
            }
        }
        // Nothing send
        return false;
    }

    private byte[] serializeObject(Object message) throws IOException {

        // If already in the right format
        if (message instanceof byte[]) {
            return (byte[]) message;
        }

        // If not, serialize it by hand
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        oos.writeObject(message);

        return baos.toByteArray();
    }
}
